<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2024/3/20
 * Time: 11:46
 */

namespace app\queue\redis;

use app\common\lib\Common;
use app\common\lib\Puppeteer;
use app\common\lib\RedisQueue;
use app\common\lib\TencentIvld;
use app\exception\IndexException;
use app\model\video\AsyncUploadVideoIvldModel;
use support\Cache;
use Webman\RedisQueue\Consumer;
use app\common\lib\TencentCos;

class AsyncVideoLink  implements Consumer
{
    // 要消费的队列名
    public $queue = 'asyncVideoLink';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    protected $resultData = [];

    // 消费
    public function consume($data)
    {
        try{

            $result = $this->handle($data);

            RedisQueue::getInstance()->saveQueue($this->queue,$data,$result);
        }catch (\Exception $e){
            RedisQueue::getInstance()->saveQueue($this->queue,$data,['error'=>$e->getMessage()]);
        }
    }

    protected function handle($data)
    {
        try{
            $requestId = $data['requestid'];
            $cacheKey = 'get_link_video_'.$requestId;
            $cacheData = [
                'progress'=>0,
                'url'=>'',
                'msg'=>'get link videoing',
            ];
            Cache::set($cacheKey,$cacheData,300);

            $videoLink = Puppeteer::getInstance()->getVideoLink($data['video_link_text']);
            $data = [
                'progress'=>100,
                'url'=>'',
                'msg'=>'get link video success',
            ];
            Cache::set($cacheKey,$data,300);

            $name = substr(md5(round(microtime(true)*10000).uniqid()),-20);
            $filePath = runtime_path('ivld/'.date('ymd').'/'.$name.'.mp4');
            Common::mkdirs(dirname($filePath));
            $res = file_put_contents($filePath,file_get_contents($videoLink));
            if($res==false){
                throw new IndexException(4020,'download video fail');
            }
            if(is_file($videoLink)){
                @unlink($videoLink);
            }

//            // 队列名
//            $queue = 'asyncVideoIvld';
//            // 数据，可以直接传数组，无需序列化
//            $data = ['requestid'=>$requestId,'filepath'=>$filePath];
//            // 投递消息
//            RedisQueue::getInstance()->sendQueue($queue, $data);

            return ['link'=>$videoLink];
        }catch (\Exception $e){
            $data = [
                'progress'=>-1,
                'url'=>'',
                'msg'=>$e->getMessage(),
            ];
            Cache::set($cacheKey,$data,300);
            return ['error'=>$e->getMessage()];
        }
    }

    // 消费失败回调
    /*
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
//        echo "consume failure\n";
//        echo $e->getMessage() . "\n";
//        // 无需反序列化
//        var_export($package);

        RedisQueue::getInstance()->saveQueue($this->queue,$package['data'],['error'=>$e->getMessage()]);
    }

}